package com.beijing.springbootclustersession.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

/**
 * @Authther: mrwu
 * @date:2021/4/1-04
 * @Description:com.beijing.springbootclustersession.interceptor
 */
public class SessionInterceptor implements HandlerInterceptor {
    private Logger logger =LoggerFactory.getLogger(SessionInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        检查session是否存在，存在则放行，不存在则返回登陆页面
        HttpSession session = request.getSession();
        Enumeration<String> attributeNames = session.getAttributeNames();
        while (attributeNames.hasMoreElements()){
            String s =attributeNames .nextElement();
            logger.info(s+"-----"+session.getAttribute("user"));
        }
        Object user = session.getAttribute("user");
        //session过期检查
        if (user!=null){
            logger.info("已登陆");
            return true;
        }
       logger.info("你未登陆");
        response.sendRedirect( request.getContextPath()+"/login/index");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
